var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session')({secret:'xxxxxx',cookie:{maxAge:20000}});

//mongo数据库配置
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var connection = mongoose.connection;
connection.on('error',function(err){
  console.log(err);
});

connection.on('open',function(){
  console.log('open');
});

//express的消息提示中间件，用于传递登陆失败的一些信息
var flash = require('express-flash');
var passport = require('passport');

//passport本地验证策略
var LocalStrategy = require('passport-local').Strategy;

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var User = require('./models/user');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


app.use(session);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());

/*
  本地验证
*/
passport.use('login', new LocalStrategy(
      function(username, password, done){
        // var user = {
        //   id:'1',
        //   username:'admin',
        //   password:'123456'
        // };
        User.findOne({'username':username},function(err,user){
          if(err){
            console.log(err);
          }

          if(!user){
            return done(null, false, { message: '用户名不存在' });
          }

          if(username !== user.username){
              return done(null, false, {message: '请正确输入用户名' });
          }
          if (password !== user.password) {
              return done(null, false, { message: '请正确输入密码' });
          }

          return done(null, user);
        });



}));


passport.use('regist', new LocalStrategy(

      function(username,password,done){
        // if(password !== validate){
        //   console.log('not same password');
        //   // return done(null, false, { message: '两次密码不一致' });
        // }
        let user_item ;
        User.findOne({'username':username},function(err,user){
          if(err){
            console.log(err);
          }else if(user){
            return done(null, false ,{ message: '用户名已存在！' });
          }
          let newUser = new User();
          console.log(newUser);
          newUser.username = username;
          newUser.password = password;
          newUser.save(function(err,result){
            if(err){
              return done(err)
            }
            return done(null, newUser);
          });
        });
      }
));
//保存user对象
passport.serializeUser(function (user,done) {
    done(null, user);
});
//删除user对象
passport.deserializeUser(function (user, done){
    done(null, user);
});

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
